package com.dianrui.fmi.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

import android.view.View;

import android.widget.ImageView;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.MyApplication;
import com.dianrui.fmi.R;
import com.dianrui.fmi.event.ChangeName;
import com.dianrui.fmi.event.ChangeProfile;
import com.dianrui.fmi.event.RfreshUserImg;
import com.dianrui.fmi.event.RfreshUserInfo;
import com.dianrui.fmi.util.BitmapUtils;
import com.dianrui.fmi.util.ConvertUtils;
import com.dianrui.fmi.util.GlideUtil;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.wheelviews.SexPicker;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * PersonalData
 */

public class PersonalDataActivity extends BaseActivity {
    private String currentsex;
    private ProgressDialog mProgressDialog;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.userimg)
    ImageView userimg;
    @BindView(R.id.personal_data_input)
    TextView personalDataInput;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.show_sex)
    TextView showSex;
    @BindView(R.id.email)
    TextView email;

    @Override
    public int getContentViewId() {
        return R.layout.activity_personaldata;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        mProgressDialog=new ProgressDialog(this);
        EventBus.getDefault().register(this);
        currentsex = "1";
        showSex.setText(getString(R.string.man));
        title.setText(getString(R.string.personal_title));
        if (!StringUtils.isEmpty(spUtils.getString("nickname"))) {
            nickname.setText(spUtils.getString("nickname"));
        }
        if (!StringUtils.isEmpty(spUtils.getString("face"))) {
            GlideUtil.loadUserImageViewSize(getApplicationContext(), spUtils.getString("face"), userimg);
        }
        if (!StringUtils.isEmpty(spUtils.getString("email"))) {
            email.setText(spUtils.getString("email"));
        }

        if (!StringUtils.isEmpty(spUtils.getString("sex"))) {
            if (spUtils.getString("sex").equals("1")) {
                showSex.setText(getString(R.string.man));
            }else {
                showSex.setText(getString(R.string.female));
            }
        }
        if (!StringUtils.isEmpty(spUtils.getString("introduce"))) {
            personalDataInput.setText(spUtils.getString("introduce"));
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 3);

            }
        }


    }


    @OnClick({R.id.back, R.id.users_img_layout, R.id.nickname_layout, R.id.sex_layout,R.id.profile_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.users_img_layout:
                choosePicUserImage();
                break;

            case R.id.profile_layout:
                startActivity(new Intent(PersonalDataActivity.this, ChangProfileActivity.class).putExtra("profile", personalDataInput.getText().toString()));
                break;

            case R.id.nickname_layout:
                startActivity(new Intent(PersonalDataActivity.this, ChangNameActivity.class).putExtra("nickname", nickname.getText().toString()));
                break;
            case R.id.sex_layout:
                final SexPicker sexPicker = new SexPicker(PersonalDataActivity.this);
                sexPicker.setDateListener(new SexPicker.OnSexCListener() {
                    @Override
                    public void onSexSelected(String sex) {
                        if (sex.equals("Male")) {
                            currentsex = "1";
                            setSex();
                        } else {
                            currentsex = "2";
                            setSex();
                        }
                        showSex.setText(sex);

                    }
                });
                if (showSex.getText().toString().equals("Female")) {
                    sexPicker.mYearWheelView.setCurrentItem(1);
                }else {
                    sexPicker.mYearWheelView.setCurrentItem(0);
                }
                sexPicker.show();

                break;



            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)//修改昵称后更新本地并上传给后台
    public void onMessageEvent(ChangeName changeName) {
        nickname.setText(changeName.name);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)//修改昵称后更新本地并上传给后台
    public void onMessageEvent(ChangeProfile changeProfile) {
        personalDataInput.setText(changeProfile.name);
    }


    //选择拍照或者相册选图
    private void choosePicUserImage() {
        MyUtil.createPhotoChooseDialog(0, 1, PersonalDataActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
            @Override
            public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                if (resultList == null && resultList.size() == 0) {
                    ToastUtil.showToast(getString(R.string.not_choose_pic));
                    return;
                }
                GlideUtil.loadUserImageViewSize(getApplicationContext(), resultList.get(0).getPhotoPath(), userimg);
                setInfoFace("face", ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight())));

            }

            @Override
            public void onHanlderFailure(int requestCode, String errorMsg) {
            }
        });
    }

    private void setInfoFace(String key, String value) {
        mProgressDialog.setMessage(getString(R.string.submiting));
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(key, value);
        OkHttpUtils.getInstance().postWithMemberToken(Url.SETINFO, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                mProgressDialog.dismiss();
                                spUtils.put("face", jsonObject.optJSONObject("data").optString("face"));
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new RfreshUserImg());
                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    private void setSex() {
        mProgressDialog.setMessage(getString(R.string.submiting));
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("sex", currentsex);
        jsonObject.addProperty("nickname", nickname.getText().toString().trim());
        jsonObject.addProperty("introduce", personalDataInput.getText().toString().trim());
        OkHttpUtils.getInstance().postWithMemberToken(Url.SETINFO, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            mProgressDialog.dismiss();
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                spUtils.put("sex", jsonObject.optJSONObject("data").optString("sex"));
                                spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                spUtils.put("introduce", jsonObject.optJSONObject("data").optString("introduce"));
                                spUtils.put("member_id", jsonObject.optJSONObject("data").optString("member_id"));
                                EventBus.getDefault().post(new RfreshUserInfo());
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(mProgressDialog!=null &&mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
        }
    }
}
